#include "user_mapper.h"
#include "QVariant"
#include "vector"
#include "QSqlError"

// UserMapper::UserMapper() {
//     this->db = QSqlDatabase::addDatabase("QODBC");
// }

// UserMapper::~UserMapper()
// {
//     this->db.close();
// }

std::vector<User> UserMapper::SelectUserInfoByPage(const int pageSize, const int pageNumber)
{
    this->db.open();
    if (pageSize <= 0) {
        throw std::invalid_argument("pageSize must be a positive integer");
    }
    if (pageNumber < 1) {
        throw std::invalid_argument("pageNumber must be at least 1");
    }
    if(!this->db.isOpen())
    {
        throw std::runtime_error("dataBase is not open");
    }
    if(!db.isValid()) {
        throw std::runtime_error("Database connection invalid");
    }
    const int offset = (pageNumber - 1) * pageSize;

    QSqlQuery query(db);
    query.prepare("SELECT user_id, nickname FROM tb_user LIMIT ? OFFSET ?");
    query.addBindValue(pageSize);
    query.addBindValue(offset);
    if (!query.exec()) {
        throw std::runtime_error("SQL execution failed: " + query.lastError().text().toStdString());
    }
    this->db.close();
    std::vector<User> result;
    result.reserve(pageSize);
    while (query.next())
    {
        result.emplace_back(
            query.value("user_id").toString(),
            query.value("nickname").toString()
            );
    }
    return result;
}

UserMapper *UserMapper::setHost(const QString &host)
{
    this->db.setHostName(host);
    return this;
}

UserMapper *UserMapper::setDatabaseName(const QString &databaseName)
{
    this->db.setDatabaseName(databaseName);
    return this;
}

UserMapper *UserMapper::setUserName(const QString &name)
{
    this->db.setUserName(name);
    return this;
}

UserMapper *UserMapper::setPassword(const QString &password)
{
    this->db.setPassword(password);
    return this;
}

QSqlDatabase UserMapper::getDb() const
{
    return db;
}
